
using B.S.NewMedical.Api.Write.Application.Command.Department;
using B.S.NewMedical.ErrorCode;
using MediatR;
using Microsoft.AspNetCore.Mvc;

namespace B.S.NewMedical.Api.Write.Controllers.Department
{
    /// <summary>
    /// 科室管理控制器
    /// 提供科室信息的增删改API接口
    /// 包含详细的日志记录和异常处理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class DepartmentsController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly ILogger<DepartmentsController> _logger;

        /// <summary>
        /// 构造函数
        /// 注入依赖的服务
        /// </summary>
        /// <param name="mediator">中介者模式，用于处理命令</param>
        /// <param name="logger">日志记录器</param>
        public DepartmentsController(IMediator mediator, ILogger<DepartmentsController> logger)
        {
            _mediator = mediator;
            _logger = logger;
            
            _logger.LogInformation("科室管理控制器初始化完成");
        }

        /// <summary>
        /// 添加科室
        /// 创建新的科室信息，包含科室名称、地址、挂号费等
        /// </summary>
        /// <param name="request">添加科室请求命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果，包含科室ID</returns>
        [HttpPost]
        public async Task<ApiResult<int>> AddDepartment(AddDepartmentsCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始添加科室，科室名称: {DepartmentName}", request.DepartmentName);
                
                // 验证请求参数
                if (string.IsNullOrWhiteSpace(request.DepartmentName))
                {
                    _logger.LogWarning("科室名称为空，请求被拒绝");
                    return new ApiResult<int>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "科室名称不能为空"
                    };
                }

                if (string.IsNullOrWhiteSpace(request.DepartmentAddr))
                {
                    _logger.LogWarning("科室地址为空，请求被拒绝");
                    return new ApiResult<int>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "科室地址不能为空"
                    };
                }

                if (request.RegistrationFee < 0)
                {
                    _logger.LogWarning("挂号费不能为负数，请求被拒绝");
                    return new ApiResult<int>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "挂号费不能为负数"
                    };
                }

                // 执行添加操作
                var result = await _mediator.Send(request, cancellationToken);
                
                _logger.LogInformation("科室添加成功，科室ID: {DepartmentId}", result.Data);
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加科室时发生异常，科室名称: {DepartmentName}", request.DepartmentName);
                return new ApiResult<int>
                {
                    Code = ApiEnum.Error,
                    Msg = $"添加科室失败: {ex.Message}"
                };
            }
        }

        /// <summary>
        /// 修改科室
        /// 更新现有科室的信息，包括名称、地址、挂号费等
        /// </summary>
        /// <param name="request">修改科室请求命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果</returns>
        [HttpPost]
        public async Task<ApiResult<int>> UpdateDepartment(UpdateDepartmentsCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始修改科室，科室ID: {DepartmentId}", request.Id);
                
                // 验证请求参数
                if (request.Id <= 0)
                {
                    _logger.LogWarning("科室ID无效，请求被拒绝");
                    return new ApiResult<int>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "科室ID无效"
                    };
                }

                if (string.IsNullOrWhiteSpace(request.DepartmentName))
                {
                    _logger.LogWarning("科室名称为空，请求被拒绝");
                    return new ApiResult<int>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "科室名称不能为空"
                    };
                }

                if (string.IsNullOrWhiteSpace(request.DepartmentAddr))
                {
                    _logger.LogWarning("科室地址为空，请求被拒绝");
                    return new ApiResult<int>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "科室地址不能为空"
                    };
                }

                if (request.RegistrationFee < 0)
                {
                    _logger.LogWarning("挂号费不能为负数，请求被拒绝");
                    return new ApiResult<int>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "挂号费不能为负数"
                    };
                }

                // 执行修改操作
                var result = await _mediator.Send(request, cancellationToken);
                
                _logger.LogInformation("科室修改成功，科室ID: {DepartmentId}", request.Id);
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "修改科室时发生异常，科室ID: {DepartmentId}", request.Id);
                return new ApiResult<int>
                {
                    Code = ApiEnum.Error,
                    Msg = $"修改科室失败: {ex.Message}"
                };
            }
        }

        /// <summary>
        /// 删除科室
        /// 软删除科室信息，将科室状态设置为已删除
        /// </summary>
        /// <param name="request">删除科室请求命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果</returns>
        [HttpPost]
        public async Task<ApiResult<int>> DeleteDepartment(DeleteDepartmentsCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始删除科室，科室ID: {DepartmentId}", request.Id);
                
                // 验证请求参数
                if (request.Id <= 0)
                {
                    _logger.LogWarning("科室ID无效，请求被拒绝");
                    return new ApiResult<int>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "科室ID无效"
                    };
                }

                // 执行删除操作
                var result = await _mediator.Send(request, cancellationToken);
                
                _logger.LogInformation("科室删除成功，科室ID: {DepartmentId}", request.Id);
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除科室时发生异常，科室ID: {DepartmentId}", request.Id);
                return new ApiResult<int>
                {
                    Code = ApiEnum.Error,
                    Msg = $"删除科室失败: {ex.Message}"
                };
            }
        }

        /// <summary>
        /// 批量删除科室
        /// 批量软删除多个科室信息
        /// </summary>
        /// <param name="request">批量删除科室请求命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果</returns>
        [HttpPost]
        public async Task<ApiResult<int>> BatchDeleteDepartment(BatchDeleteDepartmentCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始批量删除科室，科室ID列表: {DepartmentIds}", string.Join(",", request.DepartmentIds));
                
                // 验证请求参数
                if (request.DepartmentIds == null || request.DepartmentIds.Count == 0)
                {
                    _logger.LogWarning("科室ID列表为空，请求被拒绝");
                    return new ApiResult<int>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "科室ID列表不能为空"
                    };
                }

                // 验证所有ID是否有效
                foreach (var id in request.DepartmentIds)
                {
                    if (id <= 0)
                    {
                        _logger.LogWarning("存在无效的科室ID: {InvalidId}", id);
                        return new ApiResult<int>
                        {
                            Code = ApiEnum.Fail,
                            Msg = $"存在无效的科室ID: {id}"
                        };
                    }
                }

                // 执行批量删除操作
                var result = await _mediator.Send(request, cancellationToken);
                
                _logger.LogInformation("批量删除科室成功，删除数量: {Count}", request.DepartmentIds.Count);
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量删除科室时发生异常");
                return new ApiResult<int>
                {
                    Code = ApiEnum.Error,
                    Msg = $"批量删除科室失败: {ex.Message}"
                };
            }
        }
    }
} 